﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Web.Security;
using System.Security.Principal;
using Panaglobe.Silverlight.PhotoBrowser.Server;

/// <summary>
/// This is the default page that can list existing albums,
/// create new album, and so on.
/// </summary>
public partial class _Default : System.Web.UI.Page
{
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event.
    /// </summary>
    /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
    protected override void OnPreRender(EventArgs e)
    {
        if (this.displayAlbumsPanel.Visible)
        {
            SqlConnection connection = WebCommon.CreateConnection();
            SqlCommand command = new SqlCommand();
            command.Connection = connection;

            command.CommandText = "SELECT * FROM PhotoAlbums ORDER BY DateCreated";
            command.CommandType = CommandType.Text;

            using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
            {
                int albumCount = 0;

                HtmlTableRow currentRow = null;

                while (reader.Read())
                {
                    if (albumCount == 0)
                        this.albumsTable.Rows.Clear();

                    if (albumCount % 2 == 0)
                    {
                        currentRow = new HtmlTableRow();
                        this.albumsTable.Rows.Add(currentRow);
                    }

                    AlbumInfo info = new AlbumInfo()
                    {
                        ID = ((Guid)reader["ID"]).ToString(),
                        Title = (string)reader["Title"],
                        Description = (string)reader["Description"],
                        CanEdit = true,
                        HasThumbnail = (!string.IsNullOrEmpty((string)reader["ThumbnailContentType"])
                            &&reader["Thumbnail"] is byte[] && ((byte[])reader["Thumbnail"]).Length > 0)
                    };

                    PhotoAlbumDisplayBase display = (PhotoAlbumDisplayBase)this.LoadControl("PhotoAlbumDisplay.ascx");
                    display.Album = info;

                    HtmlTableCell cell = new HtmlTableCell();
                    cell.Style[HtmlTextWriterStyle.Width] = "50%";
                    cell.Style[HtmlTextWriterStyle.Height] = "100px;";
                    cell.Controls.Add(display);
                    currentRow.Cells.Add(cell);
                    albumCount++;
                }

                if (albumCount % 2 == 1)
                    currentRow.Cells.Add(new HtmlTableCell() { InnerHtml = "&nbsp;" });
            }

            this.enterEditModePanel.Visible = HttpContext.Current.User == null || !this.User.Identity.IsAuthenticated;
            this.exitEditModePanel.Visible = HttpContext.Current.User != null && this.User.Identity.IsAuthenticated;
        }

        base.OnPreRender(e);
    }

    /// <summary>
    /// Handles the Click event of the createNewAlbumLinkButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void createNewAlbumLinkButton_Click(object sender, EventArgs e)
    {
        this.displayAlbumsPanel.Visible = false;
        this.createAlbumPanel.Visible = true;
    }

    /// <summary>
    /// Handles the Click event of the cancelCreateAlbumButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void cancelCreateAlbumButton_Click(object sender, EventArgs e)
    {
        this.displayAlbumsPanel.Visible = true;
        this.createAlbumPanel.Visible = false;
    }

    /// <summary>
    /// Handles the Click event of the createAlbumButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void createAlbumButton_Click(object sender, EventArgs e)
    {
        Guid albumID = Guid.NewGuid();

        SqlConnection connection = WebCommon.CreateConnection();
        SqlCommand command = new SqlCommand();
        command.Connection = connection;

        command.CommandType = CommandType.Text;
        command.CommandText = @"INSERT PhotoAlbums
VALUES (@ID, @Title, N'', NULL, N'', GetDate(), GetDate())";
        command.Parameters.Add("@ID", SqlDbType.UniqueIdentifier).Value = albumID;
        command.Parameters.Add("@Title", SqlDbType.NVarChar, 400).Value = this.albumNameTextBox.Text;
        command.ExecuteNonQuery();

        this.Session["AlbumID"] = albumID.ToString();
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenBrowserScript",
            @"
var newWindow = window.open(""PhotoBrowser.aspx?ID=" + albumID.ToString() + @""");
if (newWindow != null)
    newWindow.focus();
else
    document.location.href=""PhotoBrowser.aspx?ID=" + albumID.ToString() + @""";
", true);

        this.displayAlbumsPanel.Visible = true;
        this.createAlbumPanel.Visible = false;

    }


    /// <summary>
    /// Handles the Click event of the enterEditModeLinkButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void enterEditModeLinkButton_Click(object sender, EventArgs e)
    {
        string[] roles = new string[0];
        string username = "EditModeUser";
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(60), false, string.Empty);
        string encryptedTicket = FormsAuthentication.Encrypt(ticket);
        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

        HttpContext.Current.Response.Cookies.Add(cookie);
        IIdentity identity = new GenericIdentity(username, "Windows");

        HttpContext.Current.User = new GenericPrincipal(identity, roles);
    }

    /// <summary>
    /// Handles the Click event of the exitEditModeLinkButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void exitEditModeLinkButton_Click(object sender, EventArgs e)
    {
        HttpContext.Current.User = null;
        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, string.Empty);
        cookie.Expires = DateTime.Now;
        HttpContext.Current.Response.Cookies.Add(cookie);
    }
}
